<template>
  <div class="main">
    <div class="header">
      <el-form :inline="true" :model="form" class="demo-form-inline" style="padding-top: 20px">
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="状态">
            <el-option label="停用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属类型">
          <el-select v-model="form.type" placeholder="所属类型">
            <el-option v-for="item in type" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="select" icon="el-icon-search">查询</el-button>
          <el-button @click="reset" icon="el-icon-refresh-right">重置</el-button>
          <el-button type="primary" @click="addNew" icon="el-icon-edit-outline">录入</el-button>
        </el-form-item>
      </el-form>
    </div>
      <div v-for="img in data" :key="img.url" style="display: inline-block;vertical-align: top;margin-top: 20px">
        <div style="display: inline-block;vertical-align: top;width: 80px;height: 80px;margin-right: 10px;cursor: pointer"   @click="imgClick(img)">
          <el-image
              style="width: 80px; height: 80px"
              :src="img.url"
          />
        </div>
      </div>
    <div class="dia">
      <el-dialog
          :title="tittle"
          :visible.sync="drawer"
          width="30%"
          class="dialog"
          :key="randomKey"
          :before-close="handleClose">
        <div style="width:100%;display: inline-block;vertical-align: top;margin-right: 20px;">
          <el-upload
              class="avatar-uploader"
              action="/api/system/picUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="token"
              :before-upload="beforeAvatarUpload"
              :key="randomKey"
              v-if="editFlag"
              style="margin-left: 50%;transform:translate(-50%);"
          >
            <img v-if="item.url" :src="item.url" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-image
              style="width: 100px; height: 100px;border-radius: 50%;margin-left:50%;transform: translate(-50%);"
              :src="item.url"
              :preview-src-list="[item.url]"
              v-else
          />
          <br><br>
          <div v-if="!editFlag">
            <span style="font-size: 16px;margin-top: 10px">上传者：{{ item.user }}</span><br><br>
            <span style="font-size: 16px">上传时间：{{ item.time }}</span><br><br>
          </div>
          <span style="font-size: 16px">状态：</span>
          <el-switch
              style="margin-top: -5px"
              v-model="item.status"
              active-color="#ff4949"
              inactive-color="#13ce66"
              active-text="停用"
              active-value="0"
              inactive-text="启用"
              inactive-value="1"
              @change="change(item)"
          >
          </el-switch>
          <br><br>
          <span style="font-size: 16px">所属类型：</span>
          <el-select v-if="editFlag" v-model="item.type" placeholder="所属类型">
            <el-option v-for="item in type" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
          <span v-else style="font-size: 16px">{{ item.type }}</span>
        </div>
        <span slot="footer" class="dialog-footer">
              <el-button v-if="!editFlag" @click="deleteMaterial" type="danger">删 除</el-button>
              <el-button @click="drawer = false">取 消</el-button>
              <el-button v-if="editFlag" @click="submit" type="primary">提 交</el-button>
            </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "@/Axios/axios";

export default {
  data() {
    return {
      form: {},
      data: [],
      item: {},
      drawer: false,
      type: [],
      editFlag: false,
      tittle: '',
      randomKey:Math.random(),
      token: {
        "token": window.sessionStorage.getItem("token"),
      },
    }
  },
  mounted() {
    this.select();
    this.$publicMethod.selectType('material_type').then(res => {
      this.type = res;
    });
  },
  methods: {
    select() {
      axios.post("materialLibrary/list", this.form).then(res => {
        if (res.code === 200) {
          this.data = res.data;
          this.data.forEach(item => {
            this.type.forEach(type => {
              if(item.type === type.code) {
                item.type = type.name;
              }
            });
          });
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      });
    },
    reset() {
      this.form = {};
      this.select();
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.$message.success("上传成功");
        this.item.url = res.data.url;
        this.item.groupId = res.data.id;
        this.randomKey = Math.random();
      }else{
        this.$message.error("图片状态非法，无法上传，请更换其他图片");
      }
    },
    beforeAvatarUpload(file) {
      const imageFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
      const isImage = imageFormats.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    change(item) {
      if(item.id !=='' && item.id !== undefined && item.id !== null) {
        axios.post("materialLibrary/changeMaterialStatus", item).then(res => {
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.handleClose();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(() => {
        });
      }
    },
    handleClose(done) {
      this.drawer = false;
      setTimeout(() => {
        this.item = {};
        this.editFlag = false;
      }, 200);
      done();
      this.select();
    },
    imgClick(item) {
      this.item = item;
      this.tittle = "查看素材";
      this.drawer = true;
    },
    addNew() {
      this.editFlag = true;
      this.tittle = "新增素材";
      this.drawer = true;
    },
    submit(){
      if(this.item.type === '' || this.item.type === null || this.item.type === undefined || this.item.url === '' || this.item.url === null || this.item.url === undefined) {
        this.$message.warning("请上传图片并选择类型后再提交");
        return;
      }
      axios.post("materialLibrary/addNew", this.item).then(res => {
        if (res.code === 200) {
          this.$message.success("新增成功");
          this.select();
          this.handleClose();
        }else{
          this.$message.error(res.msg);
        }
      }).catch(() => {});
    },
    deleteMaterial(){
      axios.delete("materialLibrary/deleteMaterial/"+this.item.id).then(res => {
        if(res.code === 200) {
          this.$message.success("删除成功");
          this.select();
          this.handleClose();
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.main {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.avatar-uploader .el-upload {
  width: 100%;
  max-width: 150px;
  aspect-ratio: 1;
}

.avatar {
  width: 100%;
  height: auto;
  aspect-ratio: 1;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: #65b5d5 1px dashed;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.body {

}
</style>